﻿var HomeController = function ($scope) {
    $.ajax({
        url: '/Data/GetMenus',
        success: function (result) {
            $scope.menuItems = result;
            $scope.selectedMenu = $scope.menuItems[0];
            $scope.$apply();
        }
    });

    $scope.selectMenu = function (menu) {
        $scope.selectedMenu = menu;
    }

    $scope.center = { Details: { Title: "Hit" }, Lat: 32.016106, Lng: 34.773102 }
    $scope.Hit = { Details: { Title: "Hit" } , Lat: 32.016106, Lng: 34.773102 }

    $scope.SelectedNode = $scope.Hit;

    $scope.setSelectedNode = function (e, node)
    {
        $scope.SelectedNode = node;
        $scope.map.infoWindows.infowindow.open($scope.map);

    }


    $scope.zoom = 16;

    $scope.checkZoom = function()
    {
        function getDistance(p1, p2) {
            var R = 6378137; // Earth’s mean radius in meter
            var dLat = rad(p2.Lat - p1.Lat);
            var dLong = rad(p2.Lng - p1.Lng);
            var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
              Math.cos(rad(p1.Lat)) * Math.cos(rad(p2.Lat)) *
              Math.sin(dLong / 2) * Math.sin(dLong / 2);
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            var d = R * c;
            return d; // returns the distance in meter
        };

        var rad = function (x) {
            return x * Math.PI / 180;
        };


        var allLocations = [$scope.Hit];
        for (var i = 0; i < $scope.menuTree.multipleSelection.length; i++) {
            var selectedItem = $scope.menuTree.multipleSelection[i];
            for (var j = 0; j < selectedItem.Locations.length; j++) {
                allLocations.push(selectedItem.Locations[j]);
            }
        }

        

        var allLocationAreInPlace = true;
        
        bounds = $scope.map.getBounds();
        if (!bounds) return;
        
        sw = bounds.getSouthWest();
        ne = bounds.getNorthEast();
        
        s = sw.lat();
        w = sw.lng();
        n = ne.lat();
        e = ne.lng();
        
        for (var i = 0; i < allLocations.length; i++) {
            if (!(allLocations[i].Lat > s && allLocations[i].Lat < n && allLocations[i].Lng > w && allLocations[i].Lng < e))
            {
                allLocationAreInPlace = false;
            }
        }
        
        if(!allLocationAreInPlace)
        {
            $scope.zoom--;
        }

    }

    $scope.$watch('zoom', function (newValue, oldValue) {
        $scope.checkZoom();
    });


    $scope.calcRoute = function () {
        var request = {
            origin: $scope.fromAddress.findText,
            destination: "מכון טכנולוגי חולון",
            travelMode: $scope.trafficType
        };

        if ($scope.directionsService) {
            $scope.directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    $scope.directionsDisplay.setDirections(response);
                    $scope.directionTiming = $scope.computeTotalTime(response);

                    // its async call!!!!!!
                    $scope.$apply();
                }
            });
        }
    }

    $scope.$on('mapInitialized', function (evt, evtMap) {
        $scope.map = evtMap;
        
        $scope.directionsService = new google.maps.DirectionsService();
        $scope.directionsDisplay = new google.maps.DirectionsRenderer();

        $scope.directionsDisplay.setMap($scope.map);
    });

    $scope.routingOptions = [
        {
            name: "רכב",
            type: google.maps.TravelMode.DRIVING
        },
        {
            name: "תחבורה ציבורית",
            type: google.maps.TravelMode.TRANSIT
        },
        {
            name: "הליכה",
            type: google.maps.TravelMode.WALKING
        },
    ];
    
    $scope.$watchCollection('menuTree.multipleSelection', function (newValue, oldValue) {

        $scope.map.setCenter(new google.maps.LatLng($scope.Hit.Lat, $scope.Hit.Lng));
        $scope.zoom = 16;
        $scope.checkZoom();
    });

    $scope.$watchGroup(['fromAddress.findText', 'trafficType'], function (newValues, oldValues, scope) {
        if ($scope.fromAddress.findText && $scope.trafficType) {
            $scope.calcRoute();
        }
    });

    $scope.$watchGroup(['fromAddress.findText', 'trafficType'], function (newValues, oldValues, scope) {
        if ($scope.fromAddress.findText && $scope.trafficType) {
            $scope.calcRoute();
        }
    });

    $scope.$watch('selectedMenu', function (newValue, oldValue) {
        if (!$scope.selectedMenu) return;
        
        if(oldValue)
            $scope.map.infoWindows.infowindow.close();

        if ($scope.selectedMenu.ShowRouting) {
            $scope.directionsDisplay.setMap($scope.map);
        }
        else {
            $scope.directionsDisplay.setMap(null);
        }

        $scope.saveOldSettings(oldValue);
        $scope.resetAllCheckBox();
        $scope.restoreSettings(newValue);
    });

    $scope.saveOldSettings = function (menu) {
        if(!menu) return;
        menu.checkedBoxes = $scope.menuTree.multipleSelection;
    }

    $scope.restoreSettings = function (menu) {
        if (menu.checkedBoxes) {
            $scope.menuTree.multipleSelection = menu.checkedBoxes;
            for (var i = 0; i < $scope.menuTree.multipleSelection.length; i++) {
                $scope.menuTree.multipleSelection[i].checked = true;
            }
            
        }
    }


    $scope.resetAllCheckBox = function () {
        for (var i = 0; i < $scope.menuTree.multipleSelection.length; i++) {
            $scope.menuTree.multipleSelection[i].checked = false;
        }
        $scope.menuTree.multipleSelection = [];
    }

    $scope.computeTotalTime = function(result) {
        var myroute = result.routes[0];
        var time = "";
        for (var i = 0; i < myroute.legs.length; i++) {
            time += myroute.legs[i].duration.text
        }

        return time;
    }

    logoClick = function () {
        $scope.map.setCenter(new google.maps.LatLng($scope.Hit.Lat, $scope.Hit.Lng));
        $scope.map.setZoom(16);
    }

}

HomeController.$inject = ['$scope'];